<script setup>
import {
    Edit,
    Delete,
    Plus,
    Search,
    Refresh,
    Check,
    Close
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import { formatDate } from '@/utils/format.js'

const form = ref({
    inputName: ''
})

//用户搜索时选中的状态
const status = ref('')

//用户列表数据模型
const userList = ref([])

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(5)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    getUserList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    getUserList()
}

// 查询用户列表
import { userListService } from '@/api/user.js'
const getUserList = async () => {
    console.log(pageNum.value, pageSize.value, status.value, form.value.inputName);
    const res = await userListService({
        pageNum: pageNum.value ? pageNum.value : null,
        pageSize: pageSize.value ? pageSize.value : null,
        status: status.value ? status.value : null,
        inputName: form.value.inputName ? form.value.inputName : null
    })
    console.log(res)
    userList.value = res.data.items
    total.value = res.data.total
}
getUserList()
// 抽屉
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore()
const visibleDrawer = ref(false)
const title = ref('')
const UserModel = ref({})
const status2 = ref('')
const onUploadSuccess = (res) => {
    UserModel.value.userPie = res.data
}
const sex = ref('')
// 添加
import { addUserService, updateUserService, deleteUserService,batchDeleteUserService } from '@/api/user.js'
import { ElMessage, ElMessageBox } from 'element-plus'

//校验
const rules = ref({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 12, message: '长度在4到12个字符', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' },
    { min: 4, max: 12, message: '长度在4到12个字符', trigger: 'blur' }],
    nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' }]
})
const RefForm = ref()
const add = async () => {
    await RefForm.value.validate(async (valid) => {
        if (!valid) {
            return
        }
        if (sex.value == '' || status2.value == '') {
            ElMessage.error('请选择性别和状态')
            return
        }
        UserModel.value.status = status2.value
        UserModel.value.sex = sex.value
        console.log(UserModel.value)
        await addUserService(UserModel.value)
        ElMessage.success('添加成功')
        visibleDrawer.value = false
        getUserList()
    })

}
// 更新
const edit = (row) => {
    //深拷贝
    UserModel.value = JSON.parse(JSON.stringify(row))
    visibleDrawer.value = true
    title.value = '修改员工'
    status2.value = row.status
    sex.value = row.sex
}

const update = async () => {
    await RefForm.value.validate(async (valid) => {
        if (!valid) {
            return
        }
        UserModel.value.status = status2.value
        console.log(UserModel.value)
        await updateUserService(UserModel.value)
        ElMessage.success('修改成功')
        visibleDrawer.value = false
        getUserList()
    })
}
// 删除
const del = async (row) => {
    ElMessageBox.confirm(
        '你确定要删除该用户信息么?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
        }
    )
        .then(async () => {
            let res = await deleteUserService(row.id)
            if (res.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getUserList()
                return
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}
// 批量删除
const ids = ref([])
const handleSelectionChange = (rows) => {
    ids.value = rows.map(v => v.id)
    console.log(ids.value);
}
const delAll = async () => {
    ElMessageBox.confirm(
        '你确定要删除选中的员工么?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
        }
    )
        .then(async () => {
            let res = await batchDeleteUserService(ids.value)
            if (res.code == 0) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getUserList()
                return
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}
</script>
<template>
    <div class="page-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span class="title">员工管理</span>
                    <div class="header-actions">
                        <el-button type="primary" @click="visibleDrawer = true, title = '添加员工', UserModel = {}, status2 = '', sex = ''" class="add-button">
                            <el-icon><Plus /></el-icon>添加员工
                        </el-button>
                        <el-button type="danger" @click="delAll" class="delete-button">
                            <el-icon><Delete /></el-icon>批量删除
                        </el-button>
                    </div>
                </div>
            </template>
            
            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="用户名">
                        <el-input 
                            v-model="form.inputName" 
                            placeholder="请输入用户名" 
                            clearable 
                            prefix-icon="Search"
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item label="账户状态">
                        <el-select v-model="status" placeholder="请选择" clearable class="custom-input">
                            <el-option label="启用" value="启用" />
                            <el-option label="禁用" value="禁用" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getUserList" class="search-button">
                            <el-icon><Search /></el-icon>搜索
                        </el-button>
                        <el-button @click="form = {}, status = ''" class="reset-button">
                            <el-icon><Refresh /></el-icon>重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 员工列表 -->
            <el-table 
                :data="userList" 
                style="width: 100%" 
                border 
                stripe
                @selection-change="handleSelectionChange"
                :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
                :row-style="{ height: '60px' }"
                :cell-style="{ padding: '8px 0' }"
                highlight-current-row>
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="用户名" prop="username" width="120" align="center" />
                <el-table-column label="昵称" prop="nickname" width="120" align="center" />
                <el-table-column label="头像" prop="userPie" width="120" align="center">
                    <template #default="{ row }">
                        <el-image 
                            v-if="row.userPie" 
                            :src="row.userPie" 
                            :preview-src-list="[row.userPie]"
                            class="avatar-image"
                        />
                        <el-avatar v-else :size="50" icon="User" />
                    </template>
                </el-table-column>
                <el-table-column label="性别" prop="sex" width="80" align="center" />
                <el-table-column label="电话号码" prop="phone" width="150" align="center" />
                <el-table-column label="状态" prop="status" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
                            {{ row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column 
                    label="更新时间" 
                    prop="updateTime" 
                    min-width="180" 
                    align="center" 
                    show-overflow-tooltip>
                    <template #default="{ row }">
                        {{ formatDate(row.updateTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center" fixed="right">
                    <template #default="{ row }">
                        <div class="operation-buttons">
                            <el-tooltip content="编辑" placement="top">
                                <el-button 
                                    v-if="row.username !== 'admin'" 
                                    :icon="Edit" 
                                    circle 
                                    type="primary" 
                                    @click="edit(row)"
                                    size="small"
                                />
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button 
                                    v-if="row.username !== 'admin'" 
                                    :icon="Delete" 
                                    circle 
                                    type="danger" 
                                    @click="del(row)"
                                    size="small"
                                />
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="暂无员工数据" />
                </template>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    background
                    @size-change="onSizeChange"
                    @current-change="onCurrentChange"
                />
            </div>
        </el-card>

        <!-- 抽屉 -->
        <el-drawer 
            v-model="visibleDrawer" 
            :title="title" 
            direction="rtl" 
            size="50%"
            :before-close="() => visibleDrawer = false"
            destroy-on-close
            :show-close="false"
            class="custom-drawer">
            <template #header>
                <div class="drawer-header">
                    <div class="drawer-title">
                        <el-icon class="title-icon"><component :is="title === '添加员工' ? Plus : Edit" /></el-icon>
                        <span>{{ title }}</span>
                    </div>
                    <el-button class="close-button" @click="visibleDrawer = false" circle>
                        <el-icon><Close /></el-icon>
                    </el-button>
                </div>
            </template>
            <div class="drawer-content">
                <el-form 
                    :model="UserModel" 
                    :rules="rules" 
                    ref="RefForm"
                    label-width="100px" 
                    class="drawer-form">
                    <el-form-item label="用户名" prop="username">
                        <el-input 
                            v-if="title === '添加员工'" 
                            v-model="UserModel.username" 
                            placeholder="请输入用户名"
                            class="custom-input"
                        />
                        <el-input 
                            v-else 
                            v-model="UserModel.username" 
                            placeholder="请输入用户名" 
                            disabled
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input 
                            show-password 
                            v-model="UserModel.password" 
                            placeholder="请输入密码" 
                            type="password"
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input 
                            v-model="UserModel.nickname" 
                            placeholder="请输入昵称"
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item label="电话号码" prop="phone">
                        <el-input 
                            v-model="UserModel.phone" 
                            placeholder="请输入电话号码"
                            class="custom-input"
                        />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-select 
                            v-model="sex" 
                            placeholder="请选择" 
                            class="custom-input">
                            <el-option label="男" value="男" />
                            <el-option label="女" value="女" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="账户状态" prop="status">
                        <el-select 
                            v-model="status2" 
                            placeholder="请选择" 
                            class="custom-input">
                            <el-option label="启用" value="启用" />
                            <el-option label="禁用" value="禁用" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="头像" prop="userPie">
                        <el-upload 
                            class="avatar-uploader" 
                            :auto-upload="true" 
                            :show-file-list="false" 
                            action="/api/upload"
                            name="file" 
                            :on-success="onUploadSuccess" 
                            :headers="{ 'Authorization': tokenStore.token }"
                        >
                            <img v-if="UserModel.userPie" :src="UserModel.userPie" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item class="drawer-footer">
                        <el-button type="primary" @click="title === '添加员工' ? add(RefForm) : update(RefForm)" class="submit-button">
                            <el-icon><Check /></el-icon>提交
                        </el-button>
                        <el-button @click="visibleDrawer = false" class="cancel-button">
                            <el-icon><Close /></el-icon>取消
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
    </div>
</template>

<style lang="scss" scoped>
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
            object-fit: cover;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);

            &:hover {
                border-color: var(--el-color-primary);
            }
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
            line-height: 178px;
        }
    }
}

.avatar-image {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>